package net.liteheaven.xblib.widget.imageview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.os.Handler;
import android.util.AttributeSet;
import android.widget.ImageView;

import net.liteheaven.xblib.common.log.XLog;

/**
 * 
 * 圆形ImageView类
 * 可以开启setImageBitmap渐变动画
 *  
 * @author  LiangYu
 * @data:  2015-1-5 下午6:42:12 
 * @version:  V1.0
 */
public class RoundImageView extends ImageView {
	private static final String TAG = "RoundImageView";
    private static final int MAX_ALPHA = 255;
    private Handler mHandler = new Handler();
    private float mCurAlpha = MAX_ALPHA;
    private Bitmap mAniBm;
    private boolean mAniEnable = true;
    private float mFrequence = 60.0f;
    private float mAnimInterval = 500;

    public RoundImageView(Context context) {
        this(context, null);
        init();
    }

    public RoundImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
        init();
    }

    public RoundImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init(){
        setScaleType(ScaleType.CENTER_CROP);
    }

    @Override
    protected void onDraw(Canvas canvas) {
    	long start = System.currentTimeMillis();
        if (mAniBm!=null){
            int w = getWidth();
            int h = getHeight();
            int wBm = mAniBm.getWidth();
            int hBm = mAniBm.getHeight();
            int r;
            if (w <= 0 || h <= 0){
                r = wBm < hBm ? wBm/2 : hBm/2;
            }
            else{
                r = w < h ? w/2 : h/2;
            }

            Paint paint = new Paint();
            paint.setAntiAlias(true);
            paint.setAlpha((int) mCurAlpha);

            Rect rectSrc = new Rect(0, 0, wBm, hBm);
            Rect rectDest = new Rect(w/2-r, h/2-r, w/2+r, h/2+r);

            canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG));
            canvas.drawBitmap(mAniBm, rectSrc, rectDest, paint);
        }else{
        	super.onDraw(canvas);
        }
        long interval = System.currentTimeMillis() - start;
		XLog.i(TAG, "onDraw spent "+ interval + " ms" + " aniBmp= "+(mAniBm!=null));
    }

    @Override
    public void setImageBitmap(Bitmap bm) {
    	if (bm == null || bm.isRecycled()){
			super.setImageBitmap(null);
			return;
		}
		
		Bitmap circleBitmap = getCircleBitmap(bm);
		
		if (!mAniEnable){
			super.setImageBitmap(circleBitmap);
			return;
		}
		
		mAniBm = circleBitmap;

		// 如果是尺寸无效，onDraw是不会执行的，就没有动画了，针对视图是warp_content的情形
		if (getWidth() == 0 || getHeight() == 0){
			Bitmap transparent = Bitmap.createBitmap(mAniBm.getWidth(), mAniBm.getHeight(), Config.ARGB_8888);
			super.setImageBitmap(transparent);
		}
		
		mHandler.removeCallbacksAndMessages(null);
		mCurAlpha = 0;
		mHandler.post(fadeInTask);
    }

    private Runnable fadeInTask = new Runnable() {
        public void run() {
            mCurAlpha += getAlphaIncrement();
            if (mCurAlpha <= MAX_ALPHA){
                mHandler.postDelayed(fadeInTask, getFrameInterval());
            }
            else{
                mCurAlpha = MAX_ALPHA;
                RoundImageView.super.setImageBitmap(mAniBm);
                mAniBm = null;
            }
            invalidate();
        }
    };

    public void setAniEnable(boolean enable){
        mAniEnable = enable;
    }

    public static Bitmap getCircleBitmap(Bitmap input) {

        if (input == null || input.isRecycled()){
            return null;
        }

        final int w = input.getWidth();
        final int h = input.getHeight();

        if (w <= 0 || h <= 0){
            return null;
        }

        final int min = w < h ? w : h;
        final int r = min/2;
        final int borderLen = r*2;
        final Rect rectSrc = new Rect(w/2-r, h/2-r, w/2+r, h/2+r);
        final Rect rectDst = new Rect(0, 0, borderLen, borderLen);

        Paint paint = new Paint();
        paint.setAntiAlias(true);

        Bitmap output = Bitmap.createBitmap(borderLen, borderLen, Config.ARGB_8888);

        Canvas canvas = new Canvas(output);
        canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG));

        canvas.drawCircle(r, r, r, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(input, rectSrc, rectDst, paint);
        return output;
    }
    
    public void setFrequence(int val){
    	mFrequence = val;
    }
    
    /**
     * 
     * 帧时间间隔单位ms
     * @throw 
     * @return int
     */
    private int getFrameInterval(){
    	return (int) (1000.0f/mFrequence + .5f);
    }
    
    /**
     * 
     * 设置动画时间 
     * @throw 
     * @return void
     */
    public void setAnimInterval(int val){
    	mAnimInterval = val;
    }
    
    /**
     * 
     * alpha增量值 
     * @throw 
     * @return float
     */
    private float getAlphaIncrement(){
    	float result = 0;
    	if (mAnimInterval > 0){
    		result = 255 * getFrameInterval() / mAnimInterval;
    	}
    	return result;
    }
}